<?php

declare(strict_types=1);

namespace App\Controller\Api;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Controller\AbstractController;
use App\Model\CommodityModel\SupplierCommodity;
use App\Service\Code\Normal;

/**
 * @Controller(prefix="/YunCangSyncGoods")
 * @author luoshumai
 */
class YunCangSyncGoodsController extends AbstractController
{
    /**
     * 获取对应sass化关务对应云仓订单捞单池里面的分页数据
     * @RequestMapping(path="getGoodsDetails", methods="post")
     * @return string[]
     */
    public function getGoodsDetails(RequestInterface $request)
    {
        $goodCodes = $request->post('goodsCodes');

        if (empty($goodCodes)) {
            return [
                'code'  => Normal::FAIL,
                'msg'   => '条码为空',
                'data'  => [],
            ];
        }

        $table =  SupplierCommodity::instance()->getTable();
        //查询对应的商品图片和详情
        $datas = SupplierCommodity::instance()->from($table . ' as sc')
            ->select(['sc.SupplierCommoditySkuCode', 'cd.Images', 'cd.Description'])
            ->join('commodityarchives_s2b as ca', 'ca.ID', '=', 'sc.CommodityArchivesID')
            ->join('commoditydescription_s2b as cd', 'cd.CommodityInfoID', '=', 'sc.CommodityArchivesID')
            ->whereIn('sc.SupplierCommoditySkuCode', $goodCodes)
            ->groupBy('sc.SupplierCommoditySkuCode')
            ->get()->toArray();

        $tmpData = [];
        foreach ($datas as $val) {

            if (!empty($val['Images'])) {

                $img = '';
                $images = json_decode($val['Images'], true);
                foreach ($images as $image) {
                    if ($image['IsMain'] == 1) {
                        $img_name = explode('/', $image['ImageUrl']);
                        $img = json_encode([
                            [
                                'url' => $image['ImageUrl'],
                                'index' => 0,
                                'isMain' => true,
                                'imageName' => end($img_name)
                            ]
                        ],320);
                    }
                }
                
                if(!empty($img)){
                    $tmpData[] = [
                        'goodsCode' => $val['SupplierCommoditySkuCode'],
                        'images'    => $img,
                        'desc'      => $val['Description'] ?? '',
                    ];
                }
            }
        }

        return [
            'code'  => Normal::SUC,
            'msg'   => '获取成功',
            'data'  => $tmpData,
        ];
    }
}
